<?php

namespace App\Http\Controllers\API\Friend;

use Illuminate\Http\Request;
use App\Http\Controllers\API\APIController;

use Auth;
use Validator;
use App\Models\API\ChatMessage;
use Illuminate\Support\Facades\Redis;

class ChatController extends APIController
{
    public function index(Request $request, $chatRoomId)
    {
    	$chatMessages = ChatMessage::where('chatroom_id', $chatRoomId)
        ->orderBy('created_at', 'desc')
        ->paginate();

        // 取得聊天数据，将其状态修改为1
        $userId = Auth::user()->id;
        $noReadMessages = ChatMessage::where([
            ['chatroom_id', $chatRoomId],
            ['companion_id', $userId],
            ['status', 0]
        ])
        ->orderBy('created_at', 'desc')
        ->get();

        foreach ($noReadMessages as $key) {
            $key->status = 1;
            $key->save();
        }

    	return response()->json($chatMessages, 200);
    }

    public function status(Request $request)
    {
        $v = Validator::make($request->all(), [
            'chatroom'      => 'required', 
            'companion_id' => 'required'
        ]);

        if ($v->fails())
        {
            return response()->json($this->setJson(false, $v->errors()), 422);
        }

        if ($v->passes())
        {
            $chatroom = $request->get('chatroom');
            $companionId = $request->get('companion_id');
            $messages = ChatMessage::where([
                ['chatroom', $chatroom],
                ['companion_id', $companionId]
            ])->update(['status', 1]);
            
            return response()->json($this->setJson(true, 'succeed'), 200);
        }
    }

    public function chat(Request $request)
    {
    	$v = Validator::make($request->all(), [
    		'user_id'      => 'required', 
            'companion_id' => 'required', 
    		'chatroom_id'  => 'required', 
    		'detail'       => 'required|max:255'
		]);

		if ($v->fails())
		{
			return response()->json($this->setJson(false, $v->errors()), 422);
		}

		if ($v->passes())
		{
			$inputData = $request->all();

            // $inputData['status'];
            // 从redis中获取用户的状态
            $status = Redis::get('user-'.$inputData['companion_id']);
            $inputData['status'] = $status; // 前端初始值0不在线|消息未读

            ChatMessage::create($inputData);

            return response()->json($this->setJson(true, 'succeed'), 200);
		}
    }

    public function destroy(Request $request, $id)
    {
    	// 今后升级
    }

    private function setJson($status, $msg)
    {
        $res = [
            'status' => $status,
            'msg'    => $msg
        ];
        return $res;
    }
}
